package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Category;
import com.itheima.bean.MyPage;
import com.itheima.bean.Setmeal;
import com.itheima.dao.CategoryDao;
import com.itheima.dto.DishDto;
import com.itheima.exception.CException;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    //注入dish和setmeal的service对象
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    //注入dao层得对象，实现对数据库的增删改查
    private CategoryDao dao;
    @Override
    public int add(Category category) {
        //调用添加方法添加菜系
        return dao.insert(category);
    }

    @Override
    public IPage<Category> findPage(MyPage page) {
        //创建Ipage的接口对象，条件查询传入查询条件
        IPage<Category> p = new Page<>(page.getPage(),page.getPageSize());
        //返回查询的数据
        return dao.selectPage(p,null);
    }

    @Override
    public int delete(long id) {
        //1.先根据前端传过来的id进行查询该菜品或套餐对象
        Category category = dao.selectById(id);
        //2.获取查询的菜品或套餐对象中的type属性
        Integer type = category.getType();
        //3.更具type属性判断是菜品还是套餐
        if (type==1){
            List<DishDto> list = dishService.findAll(id,null);
            //3.1.判断菜肴查询返回的集合有没有数据，有则不能删除抛出异常
            if (list!=null && list.size()!=0){
                throw new CException("该分类存在菜肴");
            }
        }else {
            List<Setmeal> list = setmealService.findAll(id);
            if (list!=null && list.size()!=0){
                throw new CException("该套餐分类存在套餐");
            }
        }

        return dao.deleteById(id);
    }

    @Override
    public int update(Category category) {

        return dao.updateById(category);
    }

    @Override
    public List<Category> findType(Integer type) {
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(type!=null,Category::getType,type);
        return dao.selectList(qw);
    }

    //更具id查询单个对象并返回
    @Override
    public Category findById(Long id){
        /*//创建设置条件查询对象
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        //设置查询条件
        qw.eq(Category::getId,id);*/
        //根据查询条件查询除Category对象，并返回
        return dao.selectById(id);

    }


}
